// Copyright 2022 Huawei Cloud Computing Technology Co., Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "CaeHeartbeatThread.h"
#include <linux/prctl.h>
#include <sys/prctl.h>
#include "../cae_common/CaeLogConfig.h"
#include "../cae_agent/CaeAgent.h"
#include "CaeHttpsJob.h"
#include "CaeHttpsJobThread.h"

CaeHeartbeatThread::CaeHeartbeatThread()
{
    LOGI("CaeHeartbeatThread Construct.");
    m_threadStatus = CAE_THREAD_STATUS_NEW;
}

CaeHeartbeatThread::~CaeHeartbeatThread()
{
    m_threadStatus = CAE_THREAD_STATUS_EXIT;
}

void CaeHeartbeatThread::Run()
{
    char threadName[] = "HeartbeatThread";
    int ret = prctl(PR_SET_NAME, threadName);
    if (ret < 0) {
        LOGE("Failed to prctl, error(%d): %s", errno, strerror(errno));
    }
    LOGI("CaeHeartbeatThread run.");
    while (m_threadStatus == CAE_THREAD_STATUS_RUNNING) {
        std::weak_ptr<CaeSocketAgent> weakPtr;
        ret = CaeAgent::GetInstance().m_caeHttpsJobThread->AddHttpsJob(HttpsJobType::NOTIFY_HEARTBEAT,
                                                                       nullptr, weakPtr);
        if (ret < 0) {
            LOGE("Failed to add HttpsJob.");
        }
        uint32_t interval;
        interval = static_cast<uint32_t>(atoi(CaeConfigManage::GetHeartbeatInterval().c_str()));
        interval = interval > 0 ? interval : 60;
        if (interval > 12 * 60 * 60) {
            interval = 12 * 60 * 60;
        }
        sleep(interval);
    }

    m_threadStatus = CAE_THREAD_STATUS_EXIT;
    LOGI("CaeHeartbeatThread exit.");
}